﻿//使用事件机制，模拟实现一个闹钟功能。闹钟在一有滴答（Tick）事件和响铃（Alarm）两个事件。在闹钟走时时或者响铃时，在控制台/Winform界面显示提示信息
using System;
using System.Threading;
namespace ThirdAss;
public class Clock
{
    public delegate void Tick(object sender, EventArgs e);//抵达事件委托
    public delegate void Alarm(object sender, EventArgs e);//响铃

    public event Tick? Clock_Tick;//两个事件(可谓null，否则构造函数有warning，不知道)
    public event Alarm? Clock_Alarm;

    private DateTime alarmtime;//响铃的时间
    private bool isrunning;//控制滴答状态：走/停
    public Clock(DateTime alarmtime)
    {
        this.alarmtime = alarmtime;
        this.isrunning = false;
    }
    //启动
    public void Start()
    {
        isrunning = true;
        Thread clockthread = new Thread(Run);
        clockthread.Start();
    }
    //停止
    public void Stop()
    {
        isrunning = false;
    }
    private void Run()
    {
        while (isrunning)
        {
            //抵达事件发生
            Clock_Tick?.Invoke(this, EventArgs.Empty);
            //响铃检查
            if(DateTime.Now.Hour==alarmtime.Hour && DateTime.Now.Minute == alarmtime.Minute&&DateTime.Now.Second==alarmtime.Second)
            {
                //响铃
                Clock_Alarm?.Invoke(this, EventArgs.Empty);
            }
            Thread.Sleep(1000);//每秒一次
        }
    }
}
class Program
{
    static void Main()
    {
        DateTime alarmtime = DateTime.Now.AddSeconds(30);//当前时间后30秒后响铃
        Clock clock = new Clock(alarmtime);
        //订阅抵达事件
        clock.Clock_Tick += (sender, e) =>
        {
            Console.WriteLine($"Tick:{DateTime.Now:HH:mm:ss}");
        };
        //订阅响铃事件
        clock.Clock_Alarm += (sender, e) =>
        {
            Console.WriteLine("ALARM!!!");
            clock.Stop();
        };
        //启动闹钟
        
        Console.WriteLine($"当前时间为:{DateTime.Now:HH:mm:ss}");
        clock.Start();
        Console.WriteLine($"闹钟时间为:{alarmtime:HH:mm:ss}");
        Console.WriteLine("Press any key to exit...");//半路退出
        Console.ReadKey();
        clock.Stop();
    }
}